﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using NangLuongTieuDiemDTO.DTO;
using NangLuongTieuDiemBUS;
using NangLuongTieuDiemBUS.SDK;
using DevExpress.XtraGrid.Views.Grid;
using Excel = Microsoft.Office.Interop.Excel;

namespace NangLuongTieuDiemGUI.NangLuongTieuDiemUserControl
{
    public partial class ucLapHoaDonBanHang : UserControl
    {
        #region "[khai báo biến toàn cục]"
        public DelegateShowItem closeItem = null;

        public static string m_strLocation = string.Empty;

        List<SanPhamSDK> listProducts = new List<SanPhamSDK>();

        public static bool m_IDSelect = false;
        private enum TypeProduct
        { 
            Pin,
            Acquy,
            DieuKhienSac,
            ThietBiDien
        }
        private TypeProduct GetTypeProduct(int _iLoaiSanPhamID)
        {
            int IDLoaiSanPhamChinh =NangLuongTieuDiem_Management.LoaiSanPhamChinh_SelectByPrimaryKey( NangLuongTieuDiem_Management.LoaiSanPham_SelectByPrimaryKey(_iLoaiSanPhamID).LoaiSanPhamChinhID).ID;
            switch (_iLoaiSanPhamID)
            { 
                case 1:
                    return TypeProduct.Pin;
                case 2:
                    return TypeProduct.Acquy;
                case 3:
                    return TypeProduct.DieuKhienSac;
                default:
                    return TypeProduct.ThietBiDien;
            }
        }
        #endregion

        #region "[khởi tạo]"
        public ucLapHoaDonBanHang()
        {
            InitializeComponent();
        }
        #endregion

        #region "[Thoát]"
        private void btnThoat_Click(object sender, EventArgs e)
        {
            try {
                if (closeItem != null)
                    closeItem(false);
            }
            catch (Exception ex)
            {
                InSert_LoiHeThong("btnThoat_Click", ex);
            }
        }
        #endregion

        #region "[load]"
        private void ucLapHoaDonBanHang_Load(object sender, EventArgs e)
        {
            try
            {
                txtTongCongSuat.Text = Program.m_CongSuatThietBi.ToString();
                
                #region "[cấu hình gridview]"
                //không cho sửa trên lưới
                gridView1.OptionsBehavior.Editable = false;

                //chọn full row select
                gridView1.OptionsSelection.EnableAppearanceFocusedCell = false;

                //không cho sửa trên lưới
                gridView2.OptionsBehavior.Editable = false;

                //chọn full row select
                gridView2.OptionsSelection.EnableAppearanceFocusedCell = false;

                //không cho sửa trên lưới
                gridView3.OptionsBehavior.Editable = false;

                //chọn full row select
                gridView3.OptionsSelection.EnableAppearanceFocusedCell = false;

                //không cho sửa trên lưới
                gridView4.OptionsBehavior.Editable = false;

                //chọn full row select
                gridView4.OptionsSelection.EnableAppearanceFocusedCell = false;
                #endregion

                #region "[load các thông tin lần lượt trên datagridview]"
                //load danh sách các số giờ nắng.
                LoadComboBox();

                //lấy danh sách các tấm pin
                LoadDataGridViewPin();

                //lấy danh sách các acquy
                LoadDataGridViewAcquy();

                //láy danh sách các bộ điều khiển sạc
                LoadDataGridViewDieuKhienSac();

                //lấy danh sách các thiết bị điện
                LoadDataGridViewThietBiDien();
                #endregion

                #region "[load thông tin các tấm pin và enable các control tương ứng]"
                LoadComboboxPin();
                cmbAcquy.Enabled = false;
                txtsongayduphongcupdien.Enabled = false;
                #endregion
            }
            catch (Exception ex)
            {
                InSert_LoiHeThong("ucLapHoaDonBanHang_Load", ex);
            }
        }
        #endregion

        #region "[Lấy danh sách Pin]"
        /// <summary>
        /// Lấy danh sách Pin
        /// </summary>
        private void LoadDataGridViewPin()
        {
            try
            {
                List<SanPhamDTO> list = NangLuongTieuDiemBUS.NangLuongTieuDiem_Management.SanPham_GetAll().Where(p => p.Xoa == false).ToList();
                List<SanPhamDTO> listSanPham = new List<SanPhamDTO>();
                if (list.Count > 0)
                {
                    foreach (SanPhamDTO Item in list)
                    {
                        //lấy loại sản phẩm
                        if (NangLuongTieuDiem_Management.LoaiSanPham_SelectByPrimaryKey(Item.LoaiSanPhamID).LoaiSanPhamChinhID == 1)
                        {
                            listSanPham.Add(Item);
                        }
                    }
                }
                if (listSanPham.Count > 0)
                {
                    dgvPin.DataSource = listSanPham;
                    dgvPin.RefreshDataSource();
                }
            }
            catch (Exception ex)
            {
                InSert_LoiHeThong("LoadDataGridViewPin", ex);
            }
        }
        #endregion

        #region "[lấy danh sách các thiết bị điện]"
        /// <summary>
        /// lấy danh sách các thiết bị điện
        /// </summary>
        private void LoadDataGridViewThietBiDien()
        {
            try {
                List<SanPham_ThietBiDienSDK> list = NangLuongTieuDiemBUS.NangLuongTieuDiem_Management.SanPham_GetAllElectrialEquipment();
                if(list.Count>0)
                {
                    dgvThietBiDien.DataSource = list;
                    dgvThietBiDien.RefreshDataSource();
                }
            }
            catch (Exception ex)
            {
                InSert_LoiHeThong("LoadDataGridViewThietBiDien", ex);
            }
        }
        #endregion

        #region "[lấy danh sách Điểu khiển sạc]"
        /// <summary>
        /// lấy danh sách Điểu khiển sạc
        /// </summary>
        private void LoadDataGridViewDieuKhienSac()
        {
            try {
                List<SanPham_BoDieuKhienSacSDK> list = NangLuongTieuDiemBUS.NangLuongTieuDiem_Management.SanPham_GetAllChargeController();
                if (list.Count > 0)
                {
                    dgvDieuKhienSac.DataSource = list;
                    dgvDieuKhienSac.RefreshDataSource();
                }
            }
            catch (Exception ex)
            {
                InSert_LoiHeThong("LoadDataGridViewDieuKhienSac", ex);
            }
        }
        #endregion

        #region "[lấy danh sách acquy]"
        /// <summary>
        /// lấy danh sách acquy
        /// </summary>
        private void LoadDataGridViewAcquy()
        {
            try {
                List<SanPham_AcquySDK> list = NangLuongTieuDiemBUS.NangLuongTieuDiem_Management.SanPham_GetAllAcquy();
                if (list.Count > 0)
                {
                    dgvAcquy.DataSource = list;
                    dgvAcquy.RefreshDataSource();
                }
            }
            catch (Exception ex)
            {
                InSert_LoiHeThong("LoadDataGridViewAcquy", ex);
            }
        }
        #endregion

        #region "[Tìm sản phẩm tương ứng]"
        private void btnTimSanPham_Click(object sender, EventArgs e)
        {
            try {
                ///B1. tính công suất của Pin
                ///note:tính tổng công suất các thiết bị và chia theo giờ nắng
                double tongCongSuat = double .Parse(txtTongCongSuat.Text.Trim());
                if (tongCongSuat == 0)
                    return;
                if (txtCongSuatPhatSinh.Text.Trim() != string.Empty)
                    tongCongSuat += double.Parse(txtCongSuatPhatSinh.Text.Trim());

                SoGioNangDTO sogionang = (SoGioNangDTO)cmbKhuVuc.SelectedItem;
                tongCongSuat = (tongCongSuat / sogionang.SoGioNang);
                if (rdDuPhongCupDien.Checked)
                {
                    if (txtsongayduphongcupdien.Text.Trim() != string.Empty)
                    {
                        tongCongSuat *= double.Parse(txtsongayduphongcupdien.Text);
                    }
                }
                ///B2:Chọn Tấm Pin tương ứng với công suất
                ///Note:lấy thông tin những tấm pin tương ứng> = công suất.
                List<SanPhamDTO> listPinUngVoiCongSuat = NangLuongTieuDiem_Management.SanPham_GetListPinByPower(tongCongSuat, (int)cmbPin.SelectedValue);

                ///B3: Chọn bộ điều khiển sạc tương ứng với công suất của những tấm Pin
                ///
                double tongcongSuatTamPin = 0;
                if (listPinUngVoiCongSuat.Count > 0)
                {
                    foreach (SanPhamDTO item in listPinUngVoiCongSuat)
                    {
                        tongcongSuatTamPin += item.CongSuat;
                    }
                }
                SanPham_BoDieuKhienSacSDK dieuKhienSac = NangLuongTieuDiem_Management.SanPham_GetChargeControllerByPinPower(tongcongSuatTamPin);

                ///B4: chọn Bình acquy lưu trữ.
                /// tùy theo mục dích sử dụng có những mục đích sử dụng không cần dùng acquy
                /// 
                bool isFalg = false ;
                List<SanPham_AcquySDK> lisacquy = new List<SanPham_AcquySDK>();
                if (rdDuTruAcquy.Checked || rdDungHangNgay.Checked || rdDuPhongCupDien.Checked)
                {
                    isFalg = true;

                    //lấy danh sách các acquy phù hợp.
                    lisacquy = NangLuongTieuDiem_Management.SanPham_GetListAcquyByPinPower(tongcongSuatTamPin);
                }

                ///B5: chọn bộ kích điện.
                ///nếu có chọn acquy thì mới cho chọn bộ điều khiển sạc
                SanPham_KichDienSDK itemKichDien = null;
                if (isFalg)
                {
                    try
                    {
                        itemKichDien = NangLuongTieuDiem_Management.SanPham_GetListChangeDCAC().Where(p => p.Xoa == false).FirstOrDefault();
                    }
                    catch { }
                }

                //show tất cả ra datagridview.
                ShowDataInDataGridView(listPinUngVoiCongSuat,dieuKhienSac,lisacquy,itemKichDien);
            }
            catch (Exception ex)
            {
                InSert_LoiHeThong("btnTimSanPham_Click", ex);
            }
        }
        #endregion

        #region "[Lấy danh sách các tấm pin ứng với công suất thiết bị]"
        /// <summary>
        /// Lấy danh sách các tấm pin ứng với công suất thiết bị
        /// </summary>
        /// <param name="tongCongSuat">công suất thiết bị</param>
        private void GetPinByPower(double tongCongSuat, int _LoaiPin)
        {
            try {
                List<SanPhamDTO> listPinUngVoiCongSuat = NangLuongTieuDiemBUS.NangLuongTieuDiem_Management.SanPham_GetListPinByPower(tongCongSuat,_LoaiPin);
                if (listPinUngVoiCongSuat.Count > 0)
                {
                    dgvHienThi.DataSource = listPinUngVoiCongSuat;
                    dgvHienThi.RefreshDataSource();
                }
            }
            catch (Exception ex)
            {
                InSert_LoiHeThong("GetPinByPower", ex);
            }
        }
        #endregion

        #region "[lấy danh sách số giờ nắng]"
        /// <summary>
        /// lấy danh sách số giờ nắng
        /// </summary>
        private void LoadComboBox()
        {
            try {
                List<SoGioNangDTO> list = NangLuongTieuDiemBUS.NangLuongTieuDiem_Management.SoGioNang_GetAll().Where(p => p.Xoa == false).ToList();
                if (list.Count > 0)
                {
                    cmbKhuVuc.DataSource = list;
                    cmbKhuVuc.DisplayMember = "TenKhuVuc";
                    cmbKhuVuc.ValueMember = "ID";
                }
            }
            catch (Exception ex)
            {
                InSert_LoiHeThong("LoadComboBox", ex);
            }
        }
        #endregion

        #region "[xuất ra file excel]"
        private void btnXuatRaFileExcel_Click(object sender, EventArgs e)
        {
            try {
                //
                NangLuongTieuDiemForms.frmLuuDuongDan frm = new NangLuongTieuDiemForms.frmLuuDuongDan(true);
                frm.ShowDialog();

                if (m_strLocation != string.Empty)
                //dgvHienThi.ExportToXls(m_strLocation);
                {
                    Export(gridView5, "hoadonbanhang", "Hóa Đơn Bán Hàng");
                }
            }
            catch (Exception ex)
            {
                InSert_LoiHeThong("btnXuatRaFileExcel_Click", ex);
            }
        }
        #endregion

        #region "[Hàm export ra file excel]"
            public void Export(GridView data, string sheetName, string title)
            {
                //Tạo các đối tượng Excel
                Microsoft.Office.Interop.Excel.Application oExcel = new Microsoft.Office.Interop.Excel.Application();
                Microsoft.Office.Interop.Excel.Workbooks oBooks;
                Microsoft.Office.Interop.Excel.Sheets oSheets;
                Microsoft.Office.Interop.Excel.Workbook oBook;
                Microsoft.Office.Interop.Excel.Worksheet oSheet;

                //Tạo mới một Excel WorkBook 
                //oExcel.Visible = true;
                oExcel.DisplayAlerts = false;
                oExcel.Application.SheetsInNewWorkbook = 1;
                oBooks = oExcel.Workbooks;

                oBook = (Microsoft.Office.Interop.Excel.Workbook)(oExcel.Workbooks.Add(Type.Missing));
                oSheets = oBook.Worksheets;
                oSheet = (Microsoft.Office.Interop.Excel.Worksheet)oSheets.get_Item(1);
                oSheet.Name = sheetName;

                oSheet.PageSetup.PrintGridlines = false;
                oSheet.PageSetup.PrintHeadings = false;

                // Tạo phần đầu nếu muốn
                Microsoft.Office.Interop.Excel.Range head = oSheet.get_Range("A1", "M1");
                head.MergeCells = true;
                head.Value2 = title;
                head.Font.Bold = true;
                head.Font.Name = "Tahoma";
                head.Font.Size = "18";
                head.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;

                // tao thong tin khach hang
                // Ten
                Microsoft.Office.Interop.Excel.Range ten = oSheet.get_Range("B2", "B2");
                ten.MergeCells = true;
                ten.Value2 = "Tên khách hàng: ";
                //ten.Font.Bold = true;
                ten.Font.Name = "Tahoma";
                ten.Font.Size = "10";
                ten.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignLeft;

                // so dien thoai
                Microsoft.Office.Interop.Excel.Range dienthoai = oSheet.get_Range("B3", "B3");
                dienthoai.MergeCells = true;
                dienthoai.Value2 = "Điện thoại: ";
                //dienthoai.Font.Bold = true;
                dienthoai.Font.Name = "Tahoma";
                dienthoai.Font.Size = "10";
                dienthoai.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignLeft;

                // dia chi
                Microsoft.Office.Interop.Excel.Range diachi = oSheet.get_Range("B4", "B4");
                diachi.MergeCells = true;
                diachi.Value2 = "Địa chỉ: ";
                //diachi.Font.Bold = true;
                diachi.Font.Name = "Tahoma";
                diachi.Font.Size = "10";
                diachi.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignLeft;


                // Ten detail
                Microsoft.Office.Interop.Excel.Range ten_detail = oSheet.get_Range("C2", "M2");
                ten_detail.MergeCells = true;
                ten_detail.Value2 = txtTenKhachHang.Text;
                //ten.Font.Bold = true;
                ten_detail.Font.Name = "Tahoma";
                ten_detail.Font.Size = "10";
                ten_detail.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignLeft;

                // so dien thoai detail
                Microsoft.Office.Interop.Excel.Range dienthoai_detail = oSheet.get_Range("C3", "M3");
                dienthoai_detail.MergeCells = true;
                dienthoai_detail.Value2 = txtDienThoai.Text;
                //dienthoai.Font.Bold = true;
                dienthoai_detail.Font.Name = "Tahoma";
                dienthoai_detail.Font.Size = "10";
                dienthoai_detail.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignLeft;

                // dia chi detail 
                Microsoft.Office.Interop.Excel.Range diachi_detail = oSheet.get_Range("C4", "M4");
                diachi_detail.MergeCells = true;
                diachi_detail.Value2 = txtDiaChi.Text;
                //diachi.Font.Bold = true;
                diachi_detail.Font.Name = "Tahoma";
                diachi_detail.Font.Size = "10";
                diachi_detail.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignLeft;

                // Tạo tiêu đề cột 
                Microsoft.Office.Interop.Excel.Range cl1 = oSheet.get_Range("A6", "A6");
                cl1.Value2 = "Stt";
                cl1.ColumnWidth = 5;

                Microsoft.Office.Interop.Excel.Range cl2 = oSheet.get_Range("B6", "B6");
                cl2.Value2 = "Tên sản phẩm";
                cl2.ColumnWidth = 20;

                Microsoft.Office.Interop.Excel.Range cl3 = oSheet.get_Range("C6", "C6");
                cl3.Value2 = "Tên loại sản phẩm";
                cl3.ColumnWidth = 20.0;

                Microsoft.Office.Interop.Excel.Range cl4 = oSheet.get_Range("D6", "D6");
                cl4.Value2 = "Công suất";
                cl4.ColumnWidth = 10.0;

                Microsoft.Office.Interop.Excel.Range cl5 = oSheet.get_Range("E6", "E6");
                cl5.Value2 = "Kích thước";
                cl5.ColumnWidth = 15.0;

                Microsoft.Office.Interop.Excel.Range cl6 = oSheet.get_Range("F6", "F6");
                cl6.Value2 = "Imp";
                cl6.ColumnWidth = 5.0;

                Microsoft.Office.Interop.Excel.Range cl7 = oSheet.get_Range("G6", "G6");
                cl7.Value2 = "Vmp";
                cl7.ColumnWidth = 5.0;

                Microsoft.Office.Interop.Excel.Range cl8 = oSheet.get_Range("H6", "H6");
                cl8.Value2 = "Isc";
                cl8.ColumnWidth = 5.0;

                Microsoft.Office.Interop.Excel.Range cl9 = oSheet.get_Range("I6", "I6");
                cl9.Value2 = "Voc";
                cl9.ColumnWidth = 5.0;

                Microsoft.Office.Interop.Excel.Range cl10 = oSheet.get_Range("J6", "J6");
                cl10.Value2 = "Nguồn";
                cl10.ColumnWidth = 20.0;

                Microsoft.Office.Interop.Excel.Range cl11 = oSheet.get_Range("K6", "K6");
                cl11.Value2 = "Số lượng";
                cl11.ColumnWidth = 10.0;

                Microsoft.Office.Interop.Excel.Range cl12 = oSheet.get_Range("L6", "L6");
                cl12.Value2 = "Giá";
                cl12.ColumnWidth = 10.0;

                Microsoft.Office.Interop.Excel.Range cl13 = oSheet.get_Range("M6", "M6");
                cl13.Value2 = "Ghi chú";
                cl13.ColumnWidth = 20.0;


                Microsoft.Office.Interop.Excel.Range rowHead = oSheet.get_Range("A6", "M6");
                rowHead.Font.Bold = true;

                // Kẻ viền
                rowHead.Borders.LineStyle = Microsoft.Office.Interop.Excel.Constants.xlSolid;
                // Thiết lập màu nền
                rowHead.Interior.ColorIndex = 15;
                rowHead.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;


                // Tạo mẳng đối tượng để lưu dữ toàn bồ dữ liệu trong DataTable,
                // vì dữ liệu được được gán vào các Cell trong Excel phải thông qua object thuần.



                object[,] arr = new object[data.RowCount, 13];

                //Chuyển dữ liệu từ DataTable vào mảng đối tượng
                int stt = 1;
                for (int r = 0; r < data.RowCount; r++)
                {
                    SanPhamDTO item_sanpham = new SanPhamDTO();

                    item_sanpham = (SanPhamDTO)gridView5.GetRow(r);

                    //NangLuongTieuDiem_Management.LoaiSanPham_SelectByPrimaryKey(item.LoaiSanPhamID).TenLoaiSanPham

                    arr[r, 0] = stt;                                     // cot stt
                    arr[r, 1] = item_sanpham.TenSanPham;      // cot ten san pham
                    arr[r, 2] = NangLuongTieuDiem_Management.LoaiSanPham_SelectByPrimaryKey(item_sanpham.LoaiSanPhamID).TenLoaiSanPham;
                    arr[r, 3] = item_sanpham.CongSuat;   // cot cong suat
                    arr[r, 4] = item_sanpham.Dai + " x " + item_sanpham.Rong + " x " + item_sanpham.Day;   // kich thuoc
                    arr[r, 5] = item_sanpham.Imp;     // cot Imp
                    arr[r, 6] = item_sanpham.Vmp;     // cot vmp
                    arr[r, 7] = item_sanpham.Isc;     // cot Isc
                    arr[r, 8] = item_sanpham.Voc;      // cot Voc
                    arr[r, 9] = item_sanpham.NguonNhap;  // cot nguon nhap
                    arr[r, 10] = "1";    // cot so luong
                    arr[r, 11] = item_sanpham.Gia;    // cot so luong
                    arr[r, 12] = item_sanpham.GhiChu;    // cot ghi chu

                    stt++;

                }

                //Thiết lập vùng điền dữ liệu
                int rowStart = 7;
                int columnStart = 1;

                int rowEnd = rowStart + data.RowCount - 1;
                int columnEnd = 13;

                // Ô bắt đầu điền dữ liệu
                Microsoft.Office.Interop.Excel.Range c1 = (Microsoft.Office.Interop.Excel.Range)oSheet.Cells[rowStart, columnStart];
                // Ô kết thúc điền dữ liệu
                Microsoft.Office.Interop.Excel.Range c2 = (Microsoft.Office.Interop.Excel.Range)oSheet.Cells[rowEnd, columnEnd];
                // Lấy về vùng điền dữ liệu
                Microsoft.Office.Interop.Excel.Range range = oSheet.get_Range(c1, c2);

                //Điền dữ liệu vào vùng đã thiết lập
                range.Value2 = arr;

                // Kẻ viền
                range.Borders.LineStyle = Microsoft.Office.Interop.Excel.Constants.xlSolid;

                // Căn giữa cột STT
                Microsoft.Office.Interop.Excel.Range c3 = (Microsoft.Office.Interop.Excel.Range)oSheet.Cells[rowEnd, columnStart];
                Microsoft.Office.Interop.Excel.Range c4 = oSheet.get_Range(c1, c3);
                oSheet.get_Range(c3, c4).HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;

                //save file
                object missValue = System.Reflection.Missing.Value;

                oBook.SaveAs(m_strLocation, Excel.XlFileFormat.xlWorkbookNormal, missValue, missValue, missValue, missValue, Excel.XlSaveAsAccessMode.xlExclusive, missValue, missValue, missValue, missValue, missValue);
                oBook.Close();
                oExcel.Quit();

            }
        #endregion
       

        #region "[đánh số thứ tự trên gridview Pin]"
        private void gridView1_CustomDrawCell(object sender, DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventArgs e)
        {
            try {
                if (e.Column.Name == "colSTT")
                    e.DisplayText = (e.RowHandle + 1).ToString();
                

                if (e.Column.Name == "colKichThuoc")
                { 
                    SanPhamDTO item  = (SanPhamDTO)gridView1.GetRow(e.RowHandle);
                    e.DisplayText = item.Dai.ToString() + " x " + item.Rong.ToString() + " x " + item.Day.ToString();
                }
            }
            catch (Exception ex)
            {
                InSert_LoiHeThong("gridView1_CustomDrawCell", ex);
            }
        }
        #endregion

        #region "[Dánh số thứ tự trong gridview bình acquy]"
        private void gridView2_CustomDrawCell(object sender, DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventArgs e)
        {
            try {
                if (e.Column.Name == "colSTTacquy")
                    e.DisplayText = (e.RowHandle + 1).ToString();

                if (e.Column.Name == "colThongSo")
                {
                    SanPham_AcquySDK item = (SanPham_AcquySDK)gridView2.GetRow(e.RowHandle);
                    e.DisplayText = item.HieuDienThe + "V " + item.SoAH.ToString() + "Ah";
                }
                if (e.Column.Name == "colTenAcquy")
                {
                    SanPham_AcquySDK item = (SanPham_AcquySDK)gridView2.GetRow(e.RowHandle);
                    e.DisplayText = NangLuongTieuDiem_Management.LoaiSanPham_SelectByPrimaryKey(item.LoaiSanPhamID).TenLoaiSanPham;
                }
               
            }
            catch (Exception ex)
            {
                InSert_LoiHeThong("gridView2_CustomDrawCell", ex);
            }
        }
        #endregion

        #region "[Đánh số thứ tự trong gridview bộ điều khiển sạc]"
        private void gridView3_CustomDrawCell(object sender, DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventArgs e)
        {
            try {
                if (e.Column.Name == "colSTTdks")
                    e.DisplayText = (e.RowHandle + 1).ToString();

                if (e.Column.Name == "colThongSoKT")
                {
                    SanPham_BoDieuKhienSacSDK item = (SanPham_BoDieuKhienSacSDK)gridView3.GetRow(e.RowHandle);
                    e.DisplayText = "Umax=" + item.VMax.ToString() + "V,Umin=" + item.VMin.ToString() + "V,I=" + item.Ampe.ToString() + "A";
                }
            }
            catch (Exception ex)
            {
                InSert_LoiHeThong("gridView3_CustomDrawCell", ex);
            }
        }
        #endregion

        #region "[đánh số thứ tự cho thiet bi dien]"
        private void gridView4_CustomDrawCell(object sender, DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventArgs e)
        {
            try {
                if (e.Column.Name == "colSTTTBD")
                    e.DisplayText = (e.RowHandle + 1).ToString();

                //if (e.Column.Name == "colThongSokythuat")
                //{
                //    SanPham_ThietBiDienSDK item = (SanPham_ThietBiDienSDK)gridView4.GetRow(e.RowHandle);
                //    e.DisplayText = item.ThongSoKyThuat;
                //}
            }
            catch (Exception ex)
            {
                InSert_LoiHeThong("gridView4_CustomDrawCell", ex);
            }
        }
        #endregion

     

        #region "[hiển thị chi tiết thông tin tấm PIN]"
        private void gridView1_RowCellClick(object sender, DevExpress.XtraGrid.Views.Grid.RowCellClickEventArgs e)
        {
            try
            {
                SanPhamDTO item = (SanPhamDTO)gridView1.GetRow(e.RowHandle);

                #region "[lấy thông tin tấm pin]"
                List<string> list = new List<string>();
                string loaiPin = "Loại Pin: " + NangLuongTieuDiem_Management.LoaiSanPham_SelectByPrimaryKey(item.LoaiSanPhamID).TenLoaiSanPham;
                string kichthuoc = "Kích thước(mm) Dài x Rộng x Dày:" + item.Dai.ToString() + "x" + item.Rong.ToString() + "x" + item.Day;
                string congsuatpin ="Công suất:"+ item.CongSuat.ToString()+"(W)";
                string Imp = "CĐDĐ nhỏ nhất do tấm Pin sinh ra(Imp):"+item.Imp.ToString()+"A";
                string vmp = "Điện áp nhỏ nhất do tấm Pin sinh ra(Vmp):"+item.Vmp.ToString()+"V";
                string Isc = "CĐDĐ lớn nhất do tấm Pin sinh ra(Isc):"+item.Isc.ToString()+"A";
                string Voc = "Điện áp lớn nhất do tấm Pin sinh ra(Voc):"+item.Voc.ToString()+"A";
                string nguonNhap = "Nguồn Nhập:"+item.NguonNhap;
                string GiaTien = "Giá Bán:"+item.Gia.ToString()+" vnđ";
                
                list.Add(loaiPin);
                list.Add(kichthuoc);
                list.Add(congsuatpin);
                list.Add(Imp);
                list.Add(vmp);
                list.Add(Isc);
                list.Add(Voc);
                list.Add(nguonNhap);
                list.Add(GiaTien);
                #endregion

                NangLuongTieuDiemForms.frmShowInfomation frm = new NangLuongTieuDiemForms.frmShowInfomation(list, 0);
                frm.ShowDialog();
                if (m_IDSelect)
                    GetProductByIDAndLoadDataGridView(item.ID);
            }
            catch (Exception ex)
            {
                InSert_LoiHeThong("gridView1_RowCellClick", ex);
            }
        }

        private void GetProductByIDAndLoadDataGridView(int ID)
        {
            //lấy pin theo ID 
            SanPhamDTO itemPin = null;
            try
            {
                itemPin = NangLuongTieuDiem_Management.SanPham_SelectByPrimaryKey(ID);
            }
            catch { }
            if (itemPin != null)
            {
                SanPhamSDK itemInsert = new SanPhamSDK();
                itemInsert.Count = 1;
                itemInsert.Product = itemPin;
                listProducts.Add(itemInsert);
                ShowDataInDataGridView();
                m_IDSelect = false;
            }
        }
        #endregion

        #region "[hiển thị thông tin acquy]"
        private void gridView2_RowCellClick(object sender, DevExpress.XtraGrid.Views.Grid.RowCellClickEventArgs e)
        {
            try {
                SanPham_AcquySDK item = (SanPham_AcquySDK)gridView2.GetRow(e.RowHandle);

                #region "[Lấy thông tin sản phẩm]"
                string tensanpham = "Tên Acquy:" + item.TenSanPham;
                string hesoAH ="Hệ số AH:" +item.SoAH.ToString()+" Ah";
                string hieudienthe ="Hiệu điện thế"+ item.HieuDienThe.ToString()+"V";
                string nguonnhap ="Nguồn nhập:"+ item.NguonNhap;
                string giaban ="Giá bán:"+ item.Gia.ToString()+" vnđ";
                List<string> list = new List<string>();
                list.Add(tensanpham);
                list.Add(hesoAH);
                list.Add(hieudienthe);
                list.Add(nguonnhap);
                list.Add(giaban);
                #endregion

                NangLuongTieuDiemForms.frmShowInfomation frm = new NangLuongTieuDiemForms.frmShowInfomation(list, 1);
                frm.ShowDialog();
                if (m_IDSelect)
                    GetProductByIDAndLoadDataGridView(item.ID);
            }
            catch (Exception ex)
            {
                InSert_LoiHeThong("gridView2_RowCellClick", ex);
            }
        }
        #endregion

        #region "[hiễn thị thông tin diều khiển sạc]"
        private void gridView3_RowCellClick(object sender, DevExpress.XtraGrid.Views.Grid.RowCellClickEventArgs e)
        {
            try {
                SanPham_BoDieuKhienSacSDK item = (SanPham_BoDieuKhienSacSDK)gridView3.GetRow(e.RowHandle);
                
                #region "[lấy thông tin điều khiển sạc]"
                List<string> list = new List<string>();
                string Umax ="HĐT cực đại:"+ item.VMax.ToString()+"V";
                string Umin = "HĐT cực tiểu:" + item.VMin.ToString()+"V";
                string Ampe = "CĐDĐ:" + item.Ampe + "A";
                string NguonNhap ="Nguồn nhập:" +item.NguonNhap;
                string GiaBan = "Giá bán:" + item.Gia.ToString() + " vnđ";

                list.Add(Umax);
                list.Add(Umin);
                list.Add(Ampe);
                list.Add(NguonNhap);
                list.Add(GiaBan);
                #endregion

                NangLuongTieuDiemForms.frmShowInfomation frm = new NangLuongTieuDiemForms.frmShowInfomation(list, 2);
                frm.ShowDialog();
                if (m_IDSelect)
                    GetProductByIDAndLoadDataGridView(item.ID);
            }
            catch (Exception ex)
            {
                InSert_LoiHeThong("gridView3_RowCellClick", ex);
            }
        }
        #endregion

        #region "[hiển thị thông tin thiết bị điện]"
        private void gridView4_RowCellClick(object sender, DevExpress.XtraGrid.Views.Grid.RowCellClickEventArgs e)
        {
            try {
                SanPham_ThietBiDienSDK item = (SanPham_ThietBiDienSDK)gridView4.GetRow(e.RowHandle);

                #region "[lấy thông tin thiết bị điện]"
                List<string> list = new List<string>();
                string tenthietbi ="Tên thiết bị:" +item.TenThietBi;
                string chatlieu = "Chất liệu:" + item.ChatLieu;
                string thongsokythuat = "Thông số kỹ thuật:" + item.ThongSoKyThuat;
                string nguonsang = "Nguồn sáng:" + item.NguonSang;
                string tamthunangluong = "Tấm thu năng lượng:" + item.TamThuNangLuong;
                string nguonNhap = "Nguồn nhập:" + item.NguonNhap;
                string giaban = "Giá bán:" + item.Gia.ToString() + " vnđ";

                list.Add(tenthietbi);
                list.Add(chatlieu);
                list.Add(thongsokythuat);
                list.Add(nguonsang);
                list.Add(tamthunangluong);
                list.Add(nguonNhap);
                list.Add(giaban);
                #endregion

                NangLuongTieuDiemForms.frmShowInfomation frm = new NangLuongTieuDiemForms.frmShowInfomation(list, 3);
                frm.ShowDialog();
                if (m_IDSelect)
                    GetProductByIDAndLoadDataGridView(item.ID);
            }
            catch (Exception ex)
            {
                InSert_LoiHeThong("gridView4_RowCellClick", ex);
            }
        }
        #endregion

        #region "[đánh số thứ tự]"
        private void gridView5_CustomDrawCell(object sender, DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventArgs e)
        {
            try
            {
                try
                {
                    if (e.Column.Name == "clSTT")
                        e.DisplayText = (e.RowHandle + 1).ToString();
                    
                }
                catch (Exception ex)
                {
                    InSert_LoiHeThong("gridView5_CustomDrawCell_clSTT", ex);
                }
                try
                {
                    if (e.Column.Name == "clKichThuoc")
                    {
                        SanPhamDTO item = (SanPhamDTO)gridView5.GetRow(e.RowHandle);
                        e.DisplayText = item.Dai.ToString() + "x" + item.Rong.ToString() + "x" + item.Day.ToString();
                    }
                }
                catch (Exception ex)
                {
                    InSert_LoiHeThong("gridView5_CustomDrawCell_clKichThuoc", ex);
                }
                try
                {
                    if (e.Column.Name == "clTenLoaiSanPham")
                    {
                        SanPhamDTO item = (SanPhamDTO)gridView5.GetRow(e.RowHandle);
                        e.DisplayText = NangLuongTieuDiem_Management.LoaiSanPham_SelectByPrimaryKey(item.LoaiSanPhamID).TenLoaiSanPham;
                    }
                }
                catch (Exception ex)
                {
                    InSert_LoiHeThong("gridView5_CustomDrawCell_clTenLoaiSanPham", ex);
                }
                try {
                    if (e.Column.Name == "colSoLuong")
                    {
                        SanPhamDTO item = (SanPhamDTO)gridView5.GetRow(e.RowHandle);
                        e.DisplayText = listProducts.Where(p => p.Product.ID == item.ID).First().Count.ToString();
                    }
                }
                catch (Exception ex)
                {
                    InSert_LoiHeThong("gridView5_CustomDrawCell_colSoLuong", ex);
                }

            }
            catch (Exception ex)
            {
                InSert_LoiHeThong("gridView5_CustomDrawCell", ex);
            }
        }
        #endregion

        #region "[không cho người dùng nhập số]"
        private void txtsongayduphongcupdien_KeyPress(object sender, KeyPressEventArgs e)
        {
            try {
                if (!char.IsControl(e.KeyChar) && !char.IsNumber(e.KeyChar))
                    e.Handled = true;
            }
            catch (Exception ex)
            {
                InSert_LoiHeThong("txtsongayduphongcupdien_KeyPress", ex);
            }
        }
        #endregion

        #region "[]"
        private void radioButtonB_CheckedChanged(object sender, EventArgs e)
        {
           // SetEnableTextbox(true);
            try {
                cmbAcquy.Enabled = true;
                //load danh sách các acquy lên combobox
                LoadComboboxAcquy();
                txtsongayduphongcupdien.Enabled = true;

                
            }
            catch (Exception ex)
            {
                InSert_LoiHeThong("radioButtonB_CheckedChanged", ex);
            }
        }

        #endregion

        #region "[rdhoaluoidien checked]"
        private void rdHoaLuoiDien_CheckedChanged(object sender, EventArgs e)
        {
            try {
                cmbAcquy.Enabled = false;
                txtsongayduphongcupdien.Enabled = false;
               
            }
            catch (Exception ex)
            {
                InSert_LoiHeThong("rdHoaLuoiDien_CheckedChanged", ex);
            }
        }
        #endregion

        #region "[rdDuTruTrongAcquy checked]"
        private void rdDuTruAcquy_CheckedChanged(object sender, EventArgs e)
        {
            try {

                cmbAcquy.Enabled = true;
                //load danh sách các acquy lên combobox
                LoadComboboxAcquy();
                txtsongayduphongcupdien.Enabled = false;

              
            }
            catch (Exception ex)
            {
                InSert_LoiHeThong("rdDuTruAcquy_CheckedChanged", ex);
            }
        }
        #endregion

        #region "rdDungHangNgay checked"
        private void rdDungHangNgay_CheckedChanged(object sender, EventArgs e)
        {
            try {
                cmbAcquy.Enabled = true;
                //load danh sách các acquy lên combobox
                LoadComboboxAcquy();
                txtsongayduphongcupdien.Enabled = false;

             
            }
            catch (Exception ex)
            {
                InSert_LoiHeThong("rdDungHangNgay_CheckedChanged", ex);
            }
        }
        #endregion

        #region "[load thông tin acquy lên cmb]"
        /// <summary>
        /// load thông tin acquy lên cmb
        /// </summary>
        private void LoadComboboxAcquy()
        {
            try {
                List<LoaiSanPhamDTO> list = NangLuongTieuDiem_Management.LoaiSanPham_SelectByLoaiSanPhamChinhID(2);
                if (list.Count > 0)
                {
                    cmbAcquy.DataSource = list;
                    cmbAcquy.DisplayMember = "TenLoaiSanPham";
                    cmbAcquy.ValueMember = "ID";
                }
            }
            catch (Exception ex)
            {
                InSert_LoiHeThong("LoadComboboxAcquy", ex);
            }
        }
        #endregion

        #region "[load thông tin pin lên cmb]"
        /// <summary>
        /// load thông tin pin lên cmb
        /// </summary>
        private void LoadComboboxPin()
        {
            try {
                List<LoaiSanPhamDTO> list = NangLuongTieuDiem_Management.LoaiSanPham_SelectByLoaiSanPhamChinhID(1);
                if (list.Count > 0)
                {
                    cmbPin.DataSource = list;
                    cmbPin.DisplayMember = "TenLoaiSanPham";
                    cmbPin.ValueMember = "ID";
                }
            }
            catch (Exception ex)
            {
                InSert_LoiHeThong("LoadComboboxPin", ex);
            }
        }
        #endregion

        #region "load thông tin sản phẩm vừa tìm được từ công suất các thiết bị lên datagridview"
        /// <summary>
        /// load thông tin sản phẩm vừa tìm được từ công suất các thiết bị lên datagridview
        /// </summary>
        /// <param name="_listPin">danh sách các tấm Pin</param>
        /// <param name="_dieuKhienSac">đối tượng điều khiển sạc</param>
        /// <param name="_listAcquy">danh sách các acquy</param>
        /// <param name="_kichDien">đối tượng kích điện</param>
        private void ShowDataInDataGridView(List<SanPhamDTO> _listPin, SanPham_BoDieuKhienSacSDK _dieuKhienSac,
            List<SanPham_AcquySDK> _listAcquy, SanPham_KichDienSDK _kichDien)
        {
            try
            {

                #region "[Chuyển danh sách các tấm pin thành sản phẩm]"
                if (_listPin.Count > 0)
                {
                    //listResult = _listPin;
                    foreach (SanPhamDTO item in _listPin)
                    {
                        if (listProducts.Count == 0)
                        {
                            SanPhamSDK info = new SanPhamSDK();
                            info.Product = item;
                            info.Count = 1;
                            listProducts.Add(info);
                        }
                        else
                        {
                            SanPhamSDK itemSelect = null;
                            try
                            {
                                itemSelect = listProducts.Where(p => p.Product.ID == item.ID).FirstOrDefault();
                            }
                            catch { }
                            if (itemSelect != null)
                            {
                                listProducts.Remove(itemSelect);

                                itemSelect.Count++;
                                listProducts.Add(itemSelect);
                            }
                            else
                            {
                                itemSelect = new SanPhamSDK();
                                itemSelect.Count = 1;
                                itemSelect.Product = item;
                                listProducts.Add(itemSelect);
                            }
                        }
                    }
                }
                
                #endregion

                #region "[nếu đồi tượng điều khiển sạc khác null thì chuyển thành đối tượng SanPham]"
                if (_dieuKhienSac != null)
                {
                    SanPhamDTO item = new SanPhamDTO();
                    item.ID = _dieuKhienSac.ID;
                    item.TenSanPham = _dieuKhienSac.TenSanPham;
                    item.LoaiSanPhamID = _dieuKhienSac.LoaiSanPhamID;
                    item.CongSuat = 0;
                    item.HinhDang = string.Empty;
                    item.Dai = 0;
                    item.Rong = 0;
                    item.Day = 0;
                    item.Imp = _dieuKhienSac.Ampe;
                    item.Isc = 0;
                    item.Voc = _dieuKhienSac.VMax;
                    item.Vmp = _dieuKhienSac.VMin;
                    item.NguonNhap = _dieuKhienSac.NguonNhap;
                    item.Xoa = _dieuKhienSac.Xoa;
                    item.GhiChu = _dieuKhienSac.GhiChu;
                    item.Gia = _dieuKhienSac.Gia;

                    SanPhamSDK info = new SanPhamSDK();
                    info.Count = 1;
                    info.Product = item;
                    listProducts.Add(info);
                    //listResult.Add(item);
                }
                #endregion

                #region "[chuyển danh sách Acquy thành danh sách các sản phẩm]"
                if (_listAcquy.Count > 0)
                {
                    foreach (SanPham_AcquySDK item in _listAcquy)
                    {
                        SanPhamSDK info = null;
                        try
                        {
                            info = listProducts.Where(p => p.Product.ID == item.ID).FirstOrDefault();
                        }
                        catch { }
                        if (info != null)
                        {
                            listProducts.Remove(info);
                            info.Count++;
                            listProducts.Add(info);
                        }
                        else
                        {
                            SanPhamDTO sanPham = new SanPhamDTO();
                            sanPham.ID = item.ID;
                            sanPham.TenSanPham = item.TenSanPham;
                            sanPham.LoaiSanPhamID = item.LoaiSanPhamID;
                            sanPham.CongSuat = item.SoAH;
                            sanPham.HinhDang = string.Empty;
                            sanPham.Dai = 0;
                            sanPham.Rong = 0;
                            sanPham.Day = 0;
                            sanPham.Imp = 0;
                            sanPham.Vmp = item.HieuDienThe;
                            sanPham.Isc = 0;
                            sanPham.Voc = 0;
                            sanPham.NguonNhap = item.NguonNhap;
                            sanPham.Gia = item.Gia;
                            sanPham.Xoa = item.Xoa;
                            sanPham.GhiChu = item.GhiChu;

                            info = new SanPhamSDK();
                            info.Count = 1;
                            info.Product = sanPham;
                            listProducts.Add(info);
                        }
                    }
                }
                #endregion

                #region "[Chuyển đối tượng kích điện thành SanPham]"
                if (_kichDien != null)
                {
                    SanPhamDTO item = new SanPhamDTO();
                    item.ID = _kichDien.ID;
                    item.TenSanPham = string.Empty;
                    item.LoaiSanPhamID = _kichDien.LoaiSanPhamID;
                    item.CongSuat = 0;
                    item.HinhDang = _kichDien.ThongSoKyThuat;
                    item.Dai = 0;
                    item.Rong = 0;
                    item.Day = 0;
                    item.Imp = 0;
                    item.Vmp = 0;
                    item.Isc = 0;
                    item.Voc = 0;
                    item.NguonNhap = _kichDien.NguonNhap;
                    item.Gia = _kichDien.Gia;
                    item.Xoa = _kichDien.Xoa;
                    item.GhiChu = _kichDien.GhiChu;

                    SanPhamSDK info = new SanPhamSDK();
                    info.Count = 1;
                    info.Product = item;
                    listProducts.Add(info);
                    //listResult.Add(item);
                }
                #endregion

                if (listProducts.Count > 0)
                {
                    ShowDataInDataGridView();
                }
            }
            catch (Exception ex)
            {
                InSert_LoiHeThong("ShowDataInDataGridView", ex);
            }
        }
        private void ShowDataInDataGridView()
        {
            try {
                dgvHienThi.DataSource = listProducts.Select(p => p.Product).ToList();
                dgvHienThi.RefreshDataSource();
            }
            catch { }
        }
        #endregion

        #region "[tạo menu]"
        private void gridView5_PopupMenuShowing(object sender, DevExpress.XtraGrid.Views.Grid.PopupMenuShowingEventArgs e)
        {
            try {
                GridView view = (GridView)sender;
                if (e.MenuType == GridMenuType.Row)
                {
                    int rowIndex = e.HitInfo.RowHandle;
                    DevExpress.Utils.Menu.DXMenuItem menuItem;
                    e.Menu.Items.Clear();
                    menuItem = new DevExpress.Utils.Menu.DXMenuItem("Delete", new EventHandler(DeleteRow));
                    menuItem.Tag = new RowInfo(view, rowIndex);
                    e.Menu.Items.Add(menuItem);
                }
            }
            catch(Exception ex)
            {
                InSert_LoiHeThong("gridView5_PopupMenuShowing", ex);
            }
        }
        public void DeleteRow(object sender, EventArgs e)
        {
            try
            {
                DevExpress.Utils.Menu.DXMenuItem item = (DevExpress.Utils.Menu.DXMenuItem)sender;
                RowInfo info = (RowInfo)item.Tag;
                int ID = (int)gridView1.GetRowCellValue(info.RowHandle, "ID");
                SanPhamSDK sanPham = listProducts.Where(p => p.Product.ID == ID).FirstOrDefault();
                listProducts.Remove(sanPham);
                info.View.DeleteRow(info.RowHandle);
            }
            catch (Exception ex)
            {
                InSert_LoiHeThong("DeleteRow", ex);
            }
        }
        #endregion

        #region "[Hàm insert lỗi hệ thống]"
        public void InSert_LoiHeThong(string TenHam, Exception ex)
        {
            LoiHeThongDTO lhtDto = new LoiHeThongDTO();
            lhtDto.TenLoi = ex.Message.ToString();
            lhtDto.NgayTao = DateTime.Now;
            lhtDto.TenHamBiLoi = "ucLapHoaDonBanHang_" + TenHam;
            lhtDto.SuaLoi = false;
            lhtDto.GhiChu = "";
            NangLuongTieuDiem_Management.LoiHeThong_Insert(lhtDto);
            MessageBox.Show(lhtDto.TenLoi);
        }
        #endregion 

    }
}
